<!-- 查询角色资源信息 -->
<template>
    <div>
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row :gutter="48">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="角色">
                            <!-- <a-input v-model="roleId" allow-clear placeholder="请输入资源名字" /> -->
                            <a-select v-model="roleId" placeholder="请选择" @change="getRoleResource(roleId)">
                                <a-select-option v-for="(item,i) in roleList" :value="item.id" :key="i">{{item.roleName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <!-- <a-button icon="plus" @click="add()">新增</a-button> -->
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <a-transfer
            class="tree-transfer"
            show-search
            :data-source="dataSource"
            :target-keys="targetKeys"
            :render="item => item.title"
            :show-select-all="false"
            :titles="['全部权限','选中权限']"
            @change="onChange"
        >
            <template
                slot="children"
                slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }"
            >
                <a-tree
                v-if="direction === 'left' && treeData.length > 0"
                blockNode
                checkable
                checkStrictly
                defaultExpandAll
                :checkedKeys="[...selectedKeys, ...targetKeys]"
                :treeData="treeDatas"
                @check="
                    (_, props) => {
                        onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                "
                @select="
                    (_, props) => {
                        onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                "
                />
            </template>
        </a-transfer>
    </div>
</template>

<script>
// const treeData = [
//   { key: '0-0', title: '0-0' },
//   {
//     key: '0-1',
//     title: '0-1',
//     children: [
//       { key: '0-1-01', title: '0-1-0' },
//       { key: '0-1-11', title: '0-1-1' },
//     ],
//   },
//   { key: '0-2', title: '0-3' },
// ];

// const transferDataSource = [];
// function flatten(list = []) {
//     list.forEach(item => {
//         // if(item.children){
//         //     item['disabled'] = true
//         // }
//         if(!item.children){
//             transferDataSource.push(item);
//         }
//         flatten(item.children);
//     });
// }
// flatten(JSON.parse(JSON.stringify(treeData)));

function isChecked(selectedKeys, eventKey) {
    return selectedKeys.indexOf(eventKey) !== -1;
}

function handleTreeData(data, targetKeys = []) {
    data.forEach(item => {
        item['disabled'] = targetKeys.includes(item.key);
        if (item.children) {
            item['disabled'] = true
            handleTreeData(item.children, targetKeys);
        }
    });
    return data;
}
import { columns } from './table';
import { queryRoleName , queryResourceGroup , queryResource , queryRoleResource , updateRoleResource } from '@/api/power';
export default {
    data () {
        return {
            targetKeys: [],
            dataSource: [],
            treeData: [],
            roleId: '',
            roleList: [], // 所有角色信息
        };
    },
    computed: {
        treeDatas() {
            return handleTreeData(this.treeData, this.targetKeys);
        },
    },
    created(){
        this.getRoleConfig()
        this.getAllData()
    },
    methods: {
        onChange(targetKeys) {
            console.log('Target Keys:', targetKeys);
            // this.targetKeys = targetKeys;
            // 计算出那些是删除的，那些是新增的
            const diffList = [...new Set([...targetKeys, ...this.targetKeys])].filter(item => !this.targetKeys.includes(item) || !targetKeys.includes(item))
            let isDelete = 0
            if(targetKeys.length > this.targetKeys){
                // 新增权限
                // let addList = 
                console.log('新增权限')
                console.log(diffList)
            }else{
                console.log('删除权限')
                console.log(diffList)
                isDelete = 1
            }
            this.setRoleResource(diffList,isDelete)
        },
        onChecked(_, e, checkedKeys, itemSelect) {
            console.log(_,'onchecked')
            const { eventKey } = e.node;
            itemSelect(eventKey, !isChecked(checkedKeys, eventKey));
        },
        // 查询所以资源组和所包含的资源信息
        async getAllData(){
            let _this = this
            try {
                let resourceGroupList = await _this.getResourceGroup()
                let resourceList = await _this.getResource()
                let sourceData = []
                  console.log(resourceList,"resourceList")
                console.log(resourceGroupList,"roleResourceroleResource")
                let list = resourceGroupList.map(item=>{
                    let obj = new Object({
                        title: item.groupName,
                        children: [],
                        disabled: false,
                        key: item.id + 'group'
                    })
                    resourceList.forEach(resource=>{
                        if(resource.groupId == item.id){
                            obj.children.push({
                                title: resource.description,
                                key: resource.id.toString(),
                                disabled: false,
                            })
                        }
                    })
                    // for(let i = 0; i < resourceList.length; i++){
                    //     if(resourceList[i].groupId == item.id){
                    //         obj.children.push({
                    //             title: resourceList[i].description,
                    //             key: resourceList[i].id.toString(),
                    //             disabled: false,
                    //         })
                    //     }
                    // }
                    return obj
                })
                // console.log(JSON.stringify(list),'list')
                _this.treeData = list
                _this.dataSource = resourceList.map(item=>{return {
                    title: item.description,
                    key: item.id.toString(),
                    disabled: false,}})
            } catch (error) {
                console.log(error,'error')
                this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        // 获取所有资源组信息
        getResourceGroup(){
            let _this = this
            let page = 0
            let list = []
            const fn = function(resolve,reject){
                const params = {
                    'size':99,
                    'page':page,
                }
                queryResourceGroup(params)
                .then(res=>{
                    if(res.success){
                        if(page == 0){
                            list = res.data.content
                        }else{
                            list = [...list,...res.data.content]
                        }
                        if((res.data.totalElements > (page + 1) * 99)){
                            page++;
                            fn(resolve,reject)
                        }else{
                            resolve(list)
                        }
                    }else{
                        reject(res.errMessage)
                    }
                })
            }
            return new Promise((resolve,reject)=>{
                fn(resolve,reject)
            })
        },
        // 获取所有资源信息
        getResource(){
            let _this = this
            let page = 0
            let list = []
            const fn = function(resolve,reject){
                const params = {
                    'size':99,
                    'page':page,
                }
                queryResource(params)
                .then(res=>{
                    if(res.success){
                        if(page == 0){
                            list = res.data.content
                        }else{
                            list = [...list,...res.data.content]
                        }
                        if((res.data.totalElements > (page + 1) * 99)){
                            page++;
                            fn(resolve,reject)
                        }else{
                            resolve(list)
                        }
                    }else{
                        reject(res.errMessage)
                    }
                })
            }
            return new Promise((resolve,reject)=>{
                fn(resolve,reject)
            })
        },
        // 获取所有角色配置
        getRoleConfig(){
            let _this = this
            const params = {
                'page':0,
                'size':99,
            }
            queryRoleName(params)
            .then(res=>{
                if(res.success){
                    _this.roleList = res.data.content
                    _this.roleId = res.data.content[res.data.content.length - 1].id
                    _this.getRoleResource(_this.roleId)
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取角色可访问的资源信息
        getRoleResource(id){
            let _this = this
            let page = 0
            const fn = function(){
                const params = {
                    'roleId':id,
                    'size':99,
                    'page':page,
                }
                queryRoleResource(params)
                .then(res=>{
                    if(res.success){
                        if(page == 0){
                            _this.targetKeys = res.data.content.map(item=>{
                                return item.resourceId.toString()
                            })
                        }else{
                            let list = res.data.content.map(item=>{
                                return item.resourceId.toString()
                            })
                            _this.targetKeys = [..._this.targetKeys,...list]
                        }
                        if((res.data.totalElements > (page + 1) * 99)){
                            page++;
                            fn()
                        }
                    }else{
                        _this.$notification['error']({
                            message: '提示',
                            description: res.errMessage,
                            duration: 8,
                        })
                    }
                })
            }
            fn()
        },
        // 设置角色可访问资源
        setRoleResource(resourceList,isDelete){
            let _this = this
            let index = 0
            const fn = function(resourceId){
                const params = {
                    'roleId':_this.roleId, // 角色ID
                    'resourceId':resourceId, // 资源ID
                    'isDelete':isDelete, // 是否删除，0：否，1：是
                }
                updateRoleResource(params)
                .then(res=>{
                    if(res.success){
                        if(index == (resourceList.length - 1)){
                            _this.$notification['success']({
                                message: '提示',
                                description: '设置成功',
                                duration: 8,
                            })
                            _this.getRoleResource(_this.roleId)
                        }else{
                            index++
                            fn(resourceList[index])
                        }
                    }else{
                        _this.$notification['error']({
                            message: '提示',
                            description: res.errMessage,
                            duration: 8,
                        })
                    }
                })
            }
            fn(resourceList[index])
        },
    }
}

</script>
<style scoped>

</style>